import router from 'umi/router';
import { queryUserInfo } from 'services/user';
import { config, storage, sleep } from 'utils';

export default {
  // namespace: 'app',
  state: {
    userInfo: {},
    loading: false,
  },
  subscriptions: {
    setup({ dispatch, history }) {
      const isInitial = storage.getItem('initial');
      if (!isInitial) {
        return router.push('/lodingPage');
      }
      dispatch({ type: 'query' });
    },
  },
  effects: {
    // 从中间层获取用户信息
    *query({ payload }, { call, put }) {
      const { data = {} } = yield call(queryUserInfo);
      if (data && data.ID) {
        yield put({
          type: 'updateUserInfo',
          payload: data,
        });
        if (window.location.pathname === '/login') {
          yield router.push('/');
        }
      } else if (config.openPages && !config.openPages.includes(window.location.pathname)) {
        // window.location.href = `${window.location.origin}/login`;
        yield router.push('/login');
      }
    },

    // 本地保存用户信息
    *setCurrentUser({ payload }, { put }) {
      yield put({
        type: 'updateUserInfo',
        payload: payload,
      });
    },

    /** loading */
    *doLoading(_, { put }) {
      yield put({ type: 'updateState', payload: { loading: true } });
    },
    *doLoaded(_, { put }) {
      sleep(0.2);
      yield put({ type: 'updateState', payload: { loading: false } });
    },
    /** loading */
  },
  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    updateUserInfo(state, { payload = {} }) {
      storage.setItem('UID', payload.ID);
      return {
        ...state,
        userInfo: { ...payload },
      };
    },
  },
};
